package top.broncho.gank.ui.main.rank

import androidx.lifecycle.ViewModelProviders
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.cxz.multiplestatusview.MultipleStatusView
import kotlinx.android.synthetic.main.fragment_refresh_layout.*
import kotlinx.android.synthetic.main.toolbar.*
import org.jetbrains.anko.warn

import top.broncho.gank.R
import top.broncho.gank.adapter.RankAdapter
import top.broncho.gank.bean.BaseListResponseBody
import top.broncho.gank.bean.CoinInfoBean
import top.broncho.gank.databinding.RankFragmentBinding
import top.broncho.gank.ui.activity.RankViewModel
import top.broncho.gank.ui.main.score.ScoreViewModel
import top.broncho.gank.widget.SpaceItemDecoration
import top.broncho.mvvm.base.BaseDiFragment

class RankFragment : BaseDiFragment<RankFragmentBinding>() {

    companion object {
        fun newInstance() = RankFragment()
    }

    private val viewModel by viewModels<RankViewModel> { viewModelFactory }

    override fun getLayoutId() = R.layout.rank_fragment

    /**
     * 每页数据的个数
     */
    private var pageSize = 20;

    /**
     * RecyclerView Divider
     */
    private val recyclerViewItemDecoration by lazy {
        SpaceItemDecoration(requireContext())
    }

    private val rankAdapter: RankAdapter by lazy {
        RankAdapter()
    }

    /**
     * is Refresh
     */
    private var isRefresh = true

    fun showLoading() {
        // swipeRefreshLayout.isRefreshing = isRefresh
    }

    fun hideLoading() {
        swipeRefreshLayout?.isRefreshing = false
        if (isRefresh) {
            rankAdapter.setEnableLoadMore(true)
        }
    }

    fun showError(errorMsg: String) {
        mLayoutStatusView?.showError()
        if (isRefresh) {
            rankAdapter.setEnableLoadMore(true)
        } else {
            rankAdapter.loadMoreFail()
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        viewModel.rank.observe({ lifecycle }) {
            swipeRefreshLayout.isRefreshing = false
            if (it.isFailure) {
                warn { "login failed:${it.exceptionOrNull()}" }
                showError(it.exceptionOrNull().toString())
                return@observe
            }
            mLayoutStatusView?.showContent()
            showRankList(it.getOrThrow())
        }
        if (viewModel.rank.value == null) {
            start()
        }
    }


    fun initView() {
        mLayoutStatusView = multiple_status_view
        toolbar.run {
            title = getString(R.string.score_list)
        }
        swipeRefreshLayout.run {
            setOnRefreshListener(onRefreshListener)
        }
        recyclerView.run {
            layoutManager =
                LinearLayoutManager(requireContext())
            adapter = rankAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(recyclerViewItemDecoration)
        }
        rankAdapter.run {
            bindToRecyclerView(recyclerView)
            setOnLoadMoreListener(onRequestLoadMoreListener, recyclerView)
        }
    }

    fun start() {
        mLayoutStatusView?.showLoading()
        viewModel.getRankList(1)
    }

    fun showRankList(body: BaseListResponseBody<CoinInfoBean>) {
        body.datas.let {
            rankAdapter.run {
                if (isRefresh) {
                    replaceData(it)
                } else {
                    addData(it)
                }
                pageSize = body.size
                if (body.over) {
                    loadMoreEnd(isRefresh)
                } else {
                    loadMoreComplete()
                }
            }
        }
        if (rankAdapter.data.isEmpty()) {
            mLayoutStatusView?.showEmpty()
        } else {
            mLayoutStatusView?.showContent()
        }
    }

    /**
     * RefreshListener
     */
    private val onRefreshListener = SwipeRefreshLayout.OnRefreshListener {
        isRefresh = true
        rankAdapter.setEnableLoadMore(false)
        viewModel.getRankList(1)
    }

    /**
     * LoadMoreListener
     */
    private val onRequestLoadMoreListener = BaseQuickAdapter.RequestLoadMoreListener {
        isRefresh = false
        swipeRefreshLayout.isRefreshing = false
        val page = rankAdapter.data.size / pageSize + 1
        viewModel.getRankList(page)
    }
}
